<template>
  <div class="app-container">
    <el-form
      ref="elForm"
      :model="formData"
      :disabled="$route.query.isInfo"
      :rules="rules"
      size="medium"
      label-width="100px"
    >
      <h2 style="text-align: center">办公用品入库</h2>
      <h4 class="form-header h4">基本信息</h4>
      <el-row :gutter="15">
        <!-- <el-col :span="12">
          <el-form-item label="入库编号" prop="inNo">
            <el-input
              v-model="formData.inNo"
              placeholder="请输入入库编号"
              :disabled="true"
              clearable
              :style="{ width: '100%' }"
            ></el-input>
          </el-form-item>
        </el-col>-->
        <el-col :span="12">
          <el-form-item label="入库日期" prop="inDate">
            <el-date-picker
              v-model="formData.inDate"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              :style="{ width: '100%' }"
              placeholder="请选择入库日期"
              clearable
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="操作人" prop="operUserId">
            <UserDialog disabled placeholder="请选择操作人" v-model="formData.operUserId"></UserDialog>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          placeholder="请输入多行文本备注"
          :autosize="{ minRows: 4, maxRows: 4 }"
          :style="{ width: '100%' }"
        ></el-input>
      </el-form-item>

      <h4 class="form-header h4">附件信息</h4>
      <el-form-item label prop="oss">
        <FileUploadBase :isDelete="!$route.query.isInfo" v-model="formData.oss"></FileUploadBase>
      </el-form-item>
      <h4 class="form-header h4">
        入库明细
        <el-button type="primary" plain size="mini" @click="handleAdd">增行</el-button>
        <el-button type="danger" plain size="mini" @click="handleDele">删行</el-button>
      </h4>
      <el-table :data="formData.details" :border="true" style="width: 100%">
        <el-table-column label="序号" type="index" align="center" />
        <el-table-column label="用品名称" align="center">
          <template slot-scope="scope">
            <el-form-item
              label-width="0"
              :prop="`details.${scope.$index}.goodsName`"
              :rules="rules.goodsName"
            >
              <div @click="onSelectNextUsers(scope.row, scope.$index)">
                <el-input v-model="scope.row.goodsName" readonly placeholder="选择用品名称"></el-input>
              </div>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="用品类别" prop="typeName" align="center"></el-table-column>
        <el-table-column label="单位" prop="unit" align="center"></el-table-column>
        <el-table-column label="规格" prop="spec" align="center"></el-table-column>
        <el-table-column label="单价" prop="price" align="center">
          <template slot-scope="scope">
            <el-form-item
              label-width="0"
              :prop="`details.${scope.$index}.price`"
              :rules="rules.price"
            >
              <el-input v-model="scope.row.price" placeholder="请输入单价"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="入库数量" align="center">
          <template slot-scope="scope">
            <el-form-item
              label-width="0"
              :prop="`details.${scope.$index}.inCount`"
              :rules="rules.inCount"
            >
              <el-input v-model="scope.row.inCount" placeholder="请输入入库数量"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="金额" prop="money" align="center"></el-table-column>
      </el-table>
      <el-col :span="24">
        <el-form-item label-width="0" style="text-align: center; margin-top: 30px">
          <el-button v-if="!$route.query.isInfo" type="primary" @click="submitForm">提交</el-button>
          <el-button :disabled="false" @click="resetForm">返回</el-button>
        </el-form-item>
      </el-col>
    </el-form>
    <el-dialog :title="userData.title" :visible.sync="userData.open" width="60%" append-to-body>
      <el-row type="flex" :gutter="20">
        <!--部门数据-->
        <el-col :span="5">
          <el-card shadow="never" style="height: 100%">
            <div slot="header">
              <span>分类列表</span>
            </div>
            <div class="head-container">
              <el-input
                v-model="deptName"
                placeholder="请输入分类列表"
                clearable
                size="small"
                prefix-icon="el-icon-search"
              />
              <el-tree
                :data="dict.type.sys_goods_type"
                :props="deptProps"
                :expand-on-click-node="false"
                :filter-node-method="filterNode"
                ref="tree"
                default-expand-all
                @node-click="handleNodeClick"
              />
            </div>
          </el-card>
        </el-col>
        <el-col :span="18">
          <el-table
            ref="userTable"
            :key="userData.type"
            height="500"
            v-loading="userLoading"
            :data="goodsList"
            highlight-current-row
            @current-change="changeCurrentUser"
          >
            <el-table-column type="index" align="center" label="序号" />

            <el-table-column label="名称" align="center" prop="goodsName" />
            <el-table-column label="单位" align="center" prop="unit" />
            <el-table-column label="规格" align="center" prop="spec" />
          </el-table>
          <pagination
            :total="total"
            :page.sync="queryParams1.pageNum"
            :limit.sync="queryParams1.pageSize"
            @pagination="getListGoods"
          />
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="userData.open = false">取 消</el-button>
        <el-button type="primary" @click="submitUserData">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import store from "@/store";
import { userSelect } from "@/api/system/user.js";
import { inAdd, updategIn, infoIn } from "@/api/finance/in.js";
import { listGoods } from "@/api/finance/goods.js";
import { validatPrices } from "@/utils/validate.js";

export default {
  name: "AddWzrk",
  components: {},
  dicts: ["sys_fee_subject", "sys_goods_type"],

  props: [],
  data() {
    return {
      deptProps: {
        children: "children",
        label: "label"
      },
      userData: {
        title: "查找物资",
        type: "",
        open: false
      },
      userLoading: false,
      total: 0,
      goodsList: [],

      currentRow: "",
      currentIndex: 0,
      // 部门名称
      deptName: undefined,
      queryParams1: {
        typeValue: undefined
      },
      userList: [],
      formData: {
        inNo: undefined,
        inDate: null,
        operUserId: undefined,
        details: [
          {
            goodsName: "",
            typeName: "",
            spec: "",
            unit: "",
            price: "",
            inCount: "",
            money: "",
            currentStock: ""
          }
        ]
      },
      operUserIdOptions: [],
      currentUserId: null,
      rules: {
        goodsName: [
          {
            required: true,
            message: "请选择用品名称",
            trigger: "change"
          }
        ],
        price: [
          {
            required: true,
            message: "请输入单价",
            trigger: "blur"
          },
          {
            min: 1,
            max: 99999999,
            validator: validatPrices,
            trigger: "change"
          }
        ],
        inCount: [
          {
            required: true,
            message: "请输入入库数量",
            trigger: "blur"
          }
        ],
        info: [
          {
            required: true,
            message: "请输入费用详细",
            trigger: "blur"
          }
        ],
        remark: [
          {
            required: false,
            message: "请输入多行文本备注",
            trigger: "blur"
          }
        ],
        oss: [
          {
            required: false,
            message: "附件不能为空",
            trigger: "change"
          }
        ],
        inNo: [],
        inDate: [
          {
            required: true,
            message: "请选择入库日期",
            trigger: "change"
          }
        ],
        operUserId: [
          {
            required: true,
            message: "请选择操作人",
            trigger: "change"
          }
        ]
      }
    };
  },
  computed: {},
  created() {
    this.userSelect();
    if (this.$route.query.isEdit || this.$route.query.isInfo) {
      this.getinfoFee();
    }
    this.formData.operUserId = this.$store.state.user.id;
  },
  watch: {
    "formData.details": {
      deep: true,
      handler: function(newVal, oldVal) {
        let num = 0;
        newVal.forEach(i => {
          let p = (!isNaN(Number(i.inCount)) ? Number(i.inCount) : 0) * i.price;
          i.money = (Math.round(p * 100) * 1000) / 1000 / 100;
        });
      }
    },
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },

  mounted() {},
  methods: {
    onSelectNextUsers(row, index) {
      this.currentIndex = index;
      this.currentUserId = row.goodsId;
      this.currentRow = this.goodsList.find(k => k.goodsId === row.goodsId);
      this.onSelectUsers("查找物资", "next");
    },
    onSelectUsers(title, type) {
      this.userData.title = title;
      this.userData.type = type;
      this.getListGoods();
      this.userData.open = true;
    },

    /** 查询用户列表 */
    getListGoods() {
      this.userLoading = true;
      this.queryParams1.effectStatus = 1;
      listGoods(this.addDateRange(this.queryParams1, this.dateRange)).then(
        response => {
          this.goodsList = response.rows;
          this.total = response.total;
          this.toggleSelection(this.currentRow);
          this.userLoading = false;
        }
      );
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams1.typeValue = data.value;
      this.getListGoods();
    },
    changeCurrentUser(val) {
      this.currentUserId = val.goodsId;
    },
    toggleSelection(selection) {
      if (selection) {
        this.$nextTick(() => {
          this.$refs.userTable.setCurrentRow(selection);
        });
      } else {
        this.$nextTick(() => {
          this.$refs.userTable.clearSelection();
        });
      }
    },
    submitUserData() {
      if (!this.currentUserId) {
        this.$modal.msgError("请选择物资");
        return false;
      }
      this.currentRow = this.goodsList.find(
        k => k.goodsId === this.currentUserId
      );
      console.log(this.currentRow);
      this.$set(this.formData.details, this.currentIndex, {
        ...this.currentRow
      });
      console.log(this.formData.details);

      this.userData.open = false;
    },

    userSelect() {
      userSelect().then(response => {
        this.operUserIdOptions = response.data;
      });
    },
    handleAdd() {
      this.formData.details.push({
        goodsName: "",
        typeName: "",
        spec: "",
        unit: "",
        price: "",
        inCount: "",
        money: "",
        currentStock: ""
      });
    },
    handleDele() {
      if (this.formData.details.length == 1) return;
      this.formData.details.pop();
    },
    getinfoFee() {
      infoIn(this.$route.query.id).then(response => {
        this.formData = response.data;
      });
    },
    submitForm() {
      this.$refs["elForm"].validate(valid => {
        if (valid) {
          let query = JSON.parse(JSON.stringify(this.formData));
          query.operUserName = this.operUserIdOptions.find(
            i => i.userId === query.operUserId
          ).nickName;
          if (this.formData.goodsInId != undefined) {
            updategIn(query).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.resetForm();
            });
          } else {
            inAdd(query).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.resetForm();
            });
          }
        }
      });
    },
    resetForm() {
      const obj = { path: "./wzrk" };
      this.$tab.closeOpenPage(obj);
    }
  }
};
</script>
